package com.xb.loan.admin.web.controller;

import com.xb.loan.admin.Constants;
import com.xb.loan.admin.bean.system.OssOperator;
import com.xb.loan.admin.bean.system.OssOperatorRole;
import com.xb.loan.admin.bean.system.OssRoleMenu;
import com.xb.loan.admin.service.system.OperatorRoleService;
import com.xb.loan.admin.service.system.OperatorService;
import com.xb.loan.admin.service.system.RoleMenuService;
import com.xb.loan.admin.util.DES3Encrypt;
import com.xb.loan.log.exception.BizException;
import com.xb.loan.util.AuthCodeUtil;
import com.xb.loan.util.log.DefaultLoggerFacotry;
import com.xb.loan.util.log.LogFormatTemplate4CenterOSS;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;



@Controller
public class LoginController extends BaseController {
    private final static Logger logger = DefaultLoggerFacotry.getLogger(LoginController.class);
    @Autowired
    private OperatorService operatorService;
    @Autowired
    private OperatorRoleService operatorRoleService;
    @Autowired
    private RoleMenuService roleMenuService;

    @RequestMapping(value="/login" )  
    public String showLoginForm(HttpServletRequest req, Model model,HttpServletResponse response) {
        String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
        
        String loginName = (String)req.getSession().getAttribute("paramUserName");
        model.addAttribute("loginName", loginName);
        
        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
            model.addAttribute("name_pass", "登录名或登录密码错误");
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
        	model.addAttribute("name_pass", "登录名或登录密码错误");
        } else if("authCodeError".equals(exceptionClassName)) {
        	model.addAttribute("auth_code", "请输入正确的验证码");
        }else if(exceptionClassName != null) {
        	model.addAttribute("other_code", "其他错误：" + exceptionClassName);
        }
        HttpSession session = req.getSession();
        session.setAttribute(Show_Prize_Notice, "true");

	    return "/index";
    }
    
    
    @RequestMapping(value="/success" )  
    public String success(Model model,RedirectAttributes rAttr,HttpServletRequest request,HttpServletResponse response) {
        HttpSession session=request.getSession();
        String isLogin=(String)session.getAttribute("isLogin");
        String userpassword=(String)session.getAttribute("userpassword");
        String paramUserName=(String)session.getAttribute("paramUserName");
        //-------------获取是否记住登录状态信息，完成信息回显-----------------
        if ("yes".equals(isLogin)) {
            //创建两个Cookie对象
            Cookie nameCookie = new Cookie("loginName", paramUserName);
            //设置Cookie的有效期为5天
            nameCookie.setMaxAge(60 * 60 * 24 * 5);
            //对密码进行三重加密处理
            String DES3Password = DES3Encrypt.get3DESEncrypt(userpassword, Constants.CONSTANT_PWD_ENCRYPT);
            Cookie pwdCookie = new Cookie("password", DES3Password);
            pwdCookie.setMaxAge(60 * 60 * 24 * 5);
            response.addCookie(nameCookie);
           response.addCookie(pwdCookie);
        }else{
        	//清除cookies
        	 Cookie[] cookies = request.getCookies();
        	 for (int i = 0; i < cookies.length; i++) {
        		 Cookie cookieDel = cookies[i];
        		 if ("loginName".equals(cookieDel.getName())||"password".equals(cookieDel.getName())) {
        			 cookieDel.setMaxAge(0);
        	         response.addCookie(cookieDel);
				}
			}
        }
        
	    if(userpassword != null && userpassword.length() > 0){
	        	String DES3Password = DES3Encrypt.get3DESEncrypt(userpassword,Constants.CONSTANT_PWD_ENCRYPT);
		        session.setAttribute(Constants.SESSION_LOGIN_PWD, DES3Password);
	    }
        
        
        Subject currentUser = SecurityUtils.getSubject();  
        String loginName=(String)currentUser.getPrincipal();
        
        //将登录用户名存入session
        String sessionLoginName=(String)session.getAttribute(Constants.SESSION_LOGIN_NAME);
        if(StringUtils.isEmpty(sessionLoginName)){
            session.setAttribute(Constants.SESSION_LOGIN_NAME,loginName);
        }
        
        OssOperator ossOperatorVO = operatorService.queryOperatorByLoginName(loginName);
        String loginUserType ="0";
        if(ossOperatorVO != null){
            String operatorId = ossOperatorVO.getOperatorId();
            session.setAttribute(Constants.SESSION_OPERATOR_ID, operatorId);
            loginUserType = String.valueOf(ossOperatorVO.getType());
            session.setAttribute(Constants.SESSION_LOGIN_USER_TYPE, loginUserType);
            
        }
        
        SimpleAuthorizationInfo authorizationInfo=(SimpleAuthorizationInfo)session.getAttribute(Constants.SESSION_AUTHORIZATION_INFO);
        
        //当前用户授予的权限存放到session
        if(authorizationInfo==null){
            logger.info(LogFormatTemplate4CenterOSS.LOGIN,new String[]{"login",loginName});
            authorizationInfo = new SimpleAuthorizationInfo();
            
            List<OssOperatorRole> operatorRoleVOList=operatorRoleService.queryOperatorRoleByLoginName(loginName);
            for(OssOperatorRole o:operatorRoleVOList){
                authorizationInfo.addRole(o.getRoleId());
            }

            List<OssRoleMenu> roleMenuVOList=roleMenuService.queryRoleMenuByLoginName(loginName);
            List<String> sbList = new ArrayList<String>();
            for(OssRoleMenu o:roleMenuVOList){
                authorizationInfo.addStringPermission(o.getMenuId());
                sbList.add(o.getMenuId());
            }  
            session.setAttribute(Constants.SESSION_AUTHORIZATION_INFO, authorizationInfo);
            session.setAttribute(Constants.SESSION_AUTHORIZATION_LIST, sbList);


              
        } 
        
       // return new ModelAndView("main");
        String sessoinOperationId=(String)session.getAttribute(Constants.SESSION_OPERATOR_ID );
        try {
            this.addOperateLog(request, "T_Oss_Operator", "中心OSS登录", sessoinOperationId, Constants.OPERATE_TYPE_LOGIN);
        }catch (BizException e){
            logger.error("Admin操作日志保存错误");
        }
        
        
        return "redirect:/main";
    }
    
    @RequestMapping("/index")
    public String index(Model model,RedirectAttributes rAttr,HttpServletRequest request) {
        return "index";
    }
    
    @RequestMapping("/unauthorized")
    public String unauthorized(Model model,RedirectAttributes rAttr,HttpServletRequest request) {
        return "unauthorized";
    }
    
    @RequestMapping("/logout")
    public String logout(Model model,RedirectAttributes rAttr,HttpServletRequest request) {
        HttpSession session=request.getSession();
        String sessoinOperationId=(String)session.getAttribute(Constants.SESSION_OPERATOR_ID );

        /*
         * 在有操作员访问页面时，服务器重启，session值会丢失，退出时此值为null加这样的判断
         * */
        if (sessoinOperationId != null) {
            try {
                this.addOperateLog(request, "T_Oss_Operator", "中心OSS退出", sessoinOperationId, Constants.OPERATE_TYPE_LOGOUT);
            } catch (BizException e) {
                logger.error(e.getMessage(), e);
            }
        }
        
        String loginType = (String)request.getSession().getAttribute(Constants.SESSION_LOGIN_USER_TYPE);
    	if(loginType == null || "".equals(loginType) || loginType.length() < 1){
    		loginType = "0";
    	}
    	
        Subject currentUser = SecurityUtils.getSubject();  
        currentUser.logout();
        model.addAttribute("loginUserType", loginType);
        return "logout";
    }
    
    
     @RequestMapping("/authCode")
     public void getAuthCode(Model model,RedirectAttributes rAttr,HttpServletRequest request,HttpServletResponse response) {
 
        //验证码内容
        String authCode = AuthCodeUtil.getAuthCode();  
        
        request.getSession().setAttribute(Constants.SESSION_AUTHCODE, authCode);    //将验证码保存到session中，便于以后验证  
          
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0); 
        response.setContentType("image/jpeg");
        
        try {  
            //发送图片  
            ImageIO.write(AuthCodeUtil.getAuthImg(authCode), "JPEG", response.getOutputStream());  
        } catch (IOException e){  
            e.printStackTrace();  
        }  
    }

}
